package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"moon-bird-note/models"
	"moon-bird-note/redis"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "标题内容不能为空",
		})
		return
	}
	data := models.Post{
		Title:   title,
		Content: content,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "发布失败",
		})
		return
	}
	var post models.Post
	models.DB.Where("id=?", data.ID).First(&post)
	redis_data_kry := "post_" + strconv.Itoa(int(data.ID))
	jsonData, _ := json.Marshal(post)
	redis.Rdb.Set(redis.Ctx, redis_data_kry, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}
func List(c *gin.Context) {
	var post []models.Post
	redis_data_kry := "post_list"
	redisData, _ := redis.Rdb.Get(redis.Ctx, redis_data_kry).Result()
	if redisData == "" {
		models.DB.Find(&post)
		jsonData, _ := json.Marshal(post)
		redis.Rdb.Set(redis.Ctx, redis_data_kry, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &post)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": post,
	})
	return
}
func Delete(c *gin.Context) {
	id := c.Query("id")
	redis_data_kry := "post_" + id
	redis.Rdb.Del(redis.Ctx, redis_data_kry)
	models.DB.Delete(&models.Post{}, id)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
